﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using Telerik.Web.UI;
using System.Collections;
using System.Globalization;


namespace BVVD_Website.ql_ketqua_hoctap
{
    public partial class frmDiemthi : System.Web.UI.Page
    {
        public static string mfrm = "MNU027";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                grvDiemthi.Culture = new CultureInfo("vi-VN");
                grvDiemthi.Rebind();
                rdpNGAYTHI.SelectedDate = DateTime.Now.Date;

                rdpNGAYTHI.MaxDate = DateTime.Today;
                BVVDDataContext db = new BVVDDataContext();
                //fill ddlLOPHOC
                List<LST_LOPHOC> lst_lh = (from lh in db.LST_LOPHOCs
                                           select lh).ToList();
                ddlLOPHOC.DataSource = lst_lh;
                ddlLOPHOC.DataValueField = "MALH";
                ddlLOPHOC.DataTextField = "TENLH";
                ddlLOPHOC.DataBind();

                //fill ddlMONHOC
                fillddlMONHOC();

                fillgrvDiemthi();
                grvDiemthi.DataBind();


            }
        }

        protected void ddlLOPHOC_SelectedIndexChanged(object sender, Telerik.Web.UI.DropDownListEventArgs e)
        {
            fillddlMONHOC();
            fillgrvDiemthi();
            grvDiemthi.DataBind();
        }

        protected void ddlMONHOC_SelectedIndexChanged(object sender, Telerik.Web.UI.DropDownListEventArgs e)
        {

            fillgrvDiemthi();
            grvDiemthi.DataBind();
        }


        protected void rdpNGAYTHI_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
        {
            fillgrvDiemthi();
            grvDiemthi.DataBind();
        }

        private void fillgrvDiemthi()
        {

            BVVDDataContext db = new BVVDDataContext();
            string selectedMH = ddlMONHOC.SelectedValue;
            string selectedLH = ddlLOPHOC.SelectedValue;
            DateTime selectedNT = Convert.ToDateTime(rdpNGAYTHI.DbSelectedDate);
            var list = (from hv in db.LST_HOCVIENs
                        join lhv in db.F_LOP_HOCVIENs on hv.MAHV equals lhv.MAHV into temp1
                        from tmp1 in temp1
                        join lmh in db.F_LOP_MONHOCs on tmp1.MALH equals lmh.MALH into temp2
                        from tmp2 in temp2
                        join dd in db.F_DIEMTHIs on new { LH = tmp2.MALH, MH = tmp2.MAMH, HV = tmp1.MAHV } equals new { LH = dd.MALH, MH = dd.MAMH, HV = dd.MAHV } into tmpResult
                        from re in tmpResult.DefaultIfEmpty()

                        select new
                        {
                            MALH = tmp2.MALH,
                            TENLH = tmp2.LST_LOPHOC.TENLH,
                            MAMH = tmp2.MAMH,
                            TENMH = tmp2.LST_MONHOC.TENMH,
                            MAHV = hv.MAHV,
                            TENHV = hv.HODEM + " " + hv.TENHV,
                            TRANGTHAI = re.TRANGTHAI,
                            NGAYTHI = re.NGAYTHI,
                            RECID = re.RECID != null ? re.RECID : 0,
                            GHICHU = re.GHICHU,
                            DIEM = re.DIEM,
                            LANTHI = re.LANTHI

                        }).ToList().Where(a => a.MALH == selectedLH).Where(a => a.MAMH == selectedMH).Distinct();
            if (list.Where(a => a.NGAYTHI == selectedNT).Count() > 0)
            {
                //grvDiemthi.DataSource = list.Where(a => a.NGAYTHI == selectedNT).Distinct().Union(list.Where(a => a.NGAYTHI != selectedNT).DefaultIfEmpty());
                //var list1 = (from emp in list.DefaultIfEmpty()
                //             select new
                //             {
                //                 MALH = emp.MALH,
                //                 TENLH = emp.TENLH,
                //                 MAMH = emp.MAMH,
                //                 TENMH = emp.TENMH,
                //                 MAHV = emp.MAHV,
                //                 TENHV = emp.TENHV,
                //                 TRANGTHAI = String.IsNullOrEmpty(emp.TRANGTHAI) ? "0" : "1",
                //                 NGAYTHI = emp.NGAYTHI,
                //                 RECID = emp.RECID,
                //                 GHICHU = emp.GHICHU,
                //                 DIEM = emp.DIEM,
                //                 LANTHI = emp.LANTHI


                //             }).ToList().Where(a => a.NGAYTHI != selectedNT);
                grvDiemthi.DataSource = list.Where(a => a.NGAYTHI == selectedNT).Distinct();//.Union(list1);
            }
            else
            {
                var col = (from item in list
                           select new
                           {
                               MALH = item.MALH,
                               TENLH = item.TENLH,
                               MAMH = item.MAMH,
                               TENMH = item.TENMH,
                               MAHV = item.MAHV,
                               TENHV = item.TENHV,
                               TRANGTHAI = "1",
                               NGAYTHI = selectedNT,
                               RECID = 0,
                               GHICHU = "",
                               DIEM = DBNull.Value,
                               LANTHI = DBNull.Value


                           }).ToList().Distinct();
                grvDiemthi.DataSource = col.Distinct(); ;

            }




        }

        protected void grvDiemthi_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {

            BVVDDataContext db = new BVVDDataContext();
            if (Session["user"] != null)
            {
                LST_NSD user = Session["user"] as LST_NSD;

                V_PHANQUYEN pq = (from p in db.V_PHANQUYENs
                                  where p.MAMN.Equals(mfrm) && p.MANSD.Equals(user.MANSD)
                                  select p).SingleOrDefault();
                if (pq != null)
                {
                    grvDiemthi.MasterTableView.GetItems(GridItemType.CommandItem)[0].FindControl("lbtnSave").Visible = pq.EDIT > 0 && pq.ADD > 0 && pq.DELETE > 0 ? true : false;
                }
            }


            if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
            {
                string selectedMH = ddlMONHOC.SelectedValue;
                string selectedLH = ddlLOPHOC.SelectedValue;
                DateTime selectedNH = Convert.ToDateTime(rdpNGAYTHI.DbSelectedDate);


                
                GridEditFormItem editFormItem = e.Item as GridEditFormItem;
                GridDataItem parentItem = editFormItem.ParentItem;

                RadioButtonList rblTRANGTHAI = editFormItem.FindControl("rblTRANGTHAI") as RadioButtonList;
                RadTextBox txtMALH = editFormItem.FindControl("txtMALH") as RadTextBox;
                RadTextBox txtMAMH = editFormItem.FindControl("txtMAMH") as RadTextBox;

                Label lblTENLH = editFormItem.FindControl("lblTENLH") as Label;
                Label lblTENMH = editFormItem.FindControl("lblTENMH") as Label;
                //ddl txtMAHV = editFormItem.FindControl("txtMAHV") as RadTextBox;
                RadDatePicker rdpNGAYTHI1 = editFormItem.FindControl("rdpNGAYTHI1") as RadDatePicker;



                RadDropDownList ddlMAHV = editFormItem.FindControl("ddlMAHV") as RadDropDownList;


                //---------------------------------
                var list = (from hv in db.LST_HOCVIENs
                            join lhv in db.F_LOP_HOCVIENs on hv.MAHV equals lhv.MAHV into temp1
                            from tmp1 in temp1
                            join lmh in db.F_LOP_MONHOCs on tmp1.MALH equals lmh.MALH into temp2
                            from tmp2 in temp2
                            join dd in db.F_DIEMTHIs on new { LH = tmp2.MALH, MH = tmp2.MAMH, HV = tmp1.MAHV } equals new { LH = dd.MALH, MH = dd.MAMH, HV = dd.MAHV } into tmpResult
                            from re in tmpResult.DefaultIfEmpty()

                            select new
                            {
                                MALH = tmp2.MALH,
                                TENLH = tmp2.LST_LOPHOC.TENLH,
                                MAMH = tmp2.MAMH,
                                TENMH = tmp2.LST_MONHOC.TENMH,
                                MAHV = hv.MAHV,
                                TENHV = hv.HODEM + " " + hv.TENHV,
                                TRANGTHAI = re.TRANGTHAI,
                                NGAYTHI = re.NGAYTHI,
                                FULLINFO = hv.MAHV + " - " + hv.HODEM + " " + hv.TENHV

                            }).ToList().Where(a => a.MALH == selectedLH).Where(a => a.MAMH == selectedMH).Distinct();



                //--------------------------------


                ddlMAHV.DataSource = list;
                ddlMAHV.DataTextField = "FULLINFO";
                ddlMAHV.DataValueField = "MAHV";
                ddlMAHV.DataBind();
                if (e.Item is GridEditFormInsertItem || e.Item is GridDataInsertItem)
                {



                    if (ddlLOPHOC.SelectedIndex >= 0)
                    {
                        txtMALH.Text = ddlLOPHOC.SelectedValue;
                        lblTENLH.Text = ddlLOPHOC.SelectedText;


                    }
                    else
                    {
                        lblTENLH.Text = "<a href='/ql-ketqua-hoctap/frmDiemthi.aspx'>Quay lại chọn lớp học</a>";

                    }

                    if (ddlMONHOC.SelectedIndex >= 0)
                    {

                        txtMAMH.Text = ddlMONHOC.SelectedValue;
                        lblTENMH.Text = ddlMONHOC.SelectedText;
                        
                    }
                    else
                    {
                        lblTENMH.Text = "<a href='/ql-ketqua-hoctap/frmDiemthi.aspx'>Quay lại chọn môn học</a>";
                    }
                    ddlMAHV.Enabled = true;
                    rdpNGAYTHI.Enabled = true;

                }
                else
                {
                    Label lblTRANGTHAI = editFormItem["TRANGTHAI"].FindControl("lblTRANGTHAI") as Label;
                    rblTRANGTHAI.SelectedValue = lblTRANGTHAI.Text.Equals("ACTIVE") ? "1" : "0";
                    ddlMAHV.SelectedValue = editFormItem["MAHV"].Text;
                    
                    ddlMAHV.Enabled = false;
                    rdpNGAYTHI.Enabled = false;
                    

                }



            }
        }

        protected void grvDiemthi_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            fillgrvDiemthi();

        }

        protected void grvDiemthi_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridEditFormInsertItem insertedItem = (GridEditFormInsertItem)e.Item;

            F_DIEMTHI mark = new F_DIEMTHI
            {
                MAMH = (insertedItem.FindControl("txtMAMH") as RadTextBox).Text,
                MALH = (insertedItem.FindControl("txtMALH") as RadTextBox).Text,
                MAHV = (insertedItem.FindControl("ddlMAHV") as RadDropDownList).SelectedValue,
                GHICHU = (insertedItem.FindControl("txtGHICHU") as RadTextBox).Text,
                NGAYTHI = (insertedItem.FindControl("rdpNGAYTHI1") as RadDatePicker).SelectedDate,
                TRANGTHAI = (insertedItem.FindControl("rblTRANGTHAI") as RadioButtonList).SelectedValue,
                DIEM = Convert.ToDecimal((insertedItem.FindControl("txtDIEM") as RadNumericTextBox).Value),
                LANTHI = Convert.ToInt32((insertedItem.FindControl("txtLANTHI") as RadNumericTextBox).Value)


            };
            BVVDDataContext db = new BVVDDataContext();
            db.F_DIEMTHIs.InsertOnSubmit(mark);
            try
            {
                db.SubmitChanges();
                rnAlert.Text = "Nhập điểm cho <font color='red'> " + mark.LST_HOCVIEN.HODEM + " " + mark.LST_HOCVIEN.TENHV + "</font> ở lớp <font color='red'> " + mark.LST_LOPHOC.TENLH + "</font> thành công ";
            }
            catch (Exception ex)
            {
                rnAlert.Text = "Có lỗi xảy ra \n <br /> Nguyên nhân : " + ex.Message;

            }


            rnAlert.Show();
        }

        protected void grvDiemthi_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridDataItem item = (GridDataItem)e.Item;
            string recid = item.OwnerTableView.DataKeyValues[item.ItemIndex]["RECID"].ToString();
            BVVDDataContext db = new BVVDDataContext();
            F_DIEMTHI mark = (from dm in db.F_DIEMTHIs
                              where dm.RECID.ToString().Equals(recid)
                              select dm).SingleOrDefault();
            string delAlert = "Xóa  điểm của <font color='red'> " + mark.LST_HOCVIEN.HODEM + " " + mark.LST_HOCVIEN.TENHV + "</font> ở lớp <font color='red'> " + mark.LST_LOPHOC.TENLH + "</font> thành công ";
            db.F_DIEMTHIs.DeleteOnSubmit(mark);


            try
            {
                db.SubmitChanges();
                rnAlert.Text = delAlert;
            }
            catch (Exception ex)
            {
                rnAlert.Text = "Có lỗi xảy ra. \n <br /> Nguyên nhân : " + ex.Message;
            }

            rnAlert.Show();
        }

        protected void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            BVVDDataContext db = new BVVDDataContext();
            var list = (from l in db.LST_HOCVIENs
                        where l.TRANGTHAI.Equals("1")
                        select new
                        {
                            NAME = l.HODEM + " " + l.TENHV + " " + l.MAHV + " " + l.NGAYSINH,
                            MAHV = l.MAHV,
                            FULLNAME = l.HODEM + " " + l.TENHV,
                            NGAYSINH = l.NGAYSINH
                        }).ToList();
            e.Result = list;
        }


        protected void grvDiemthi_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            BVVDDataContext db = new BVVDDataContext();
            GridEditableItem editedItem = e.Item as GridEditableItem;
            string recid = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["RECID"].ToString();

            F_DIEMTHI mark = (from item in db.F_DIEMTHIs
                              where item.RECID.ToString().Equals(recid)
                              select item).SingleOrDefault();


            try
            {

                mark.DIEM = Convert.ToDecimal((editedItem.FindControl("txtDIEM") as RadNumericTextBox).Value);
                mark.LANTHI = Convert.ToInt32((editedItem.FindControl("txtLANTHI") as RadNumericTextBox).Value);
                mark.GHICHU = (editedItem.FindControl("txtGHICHU") as RadTextBox).Text;
                mark.TRANGTHAI = (editedItem.FindControl("rblTRANGTHAI") as RadioButtonList).SelectedValue;
                db.SubmitChanges();
                rnAlert.Text = "Cập nhật điểm thành công học viên có mã <font color='red'>  " + mark.MAHV + "</font>";
            }
            catch (Exception ex)
            {
                rnAlert.Text = "Có lỗi xảy ra. \n <br /> Nguyên nhân : " + ex.Message;
            }

            rnAlert.Show();
            rdpNGAYTHI.Enabled = true;
        }

        private void fillddlMONHOC()
        {
            BVVDDataContext db = new BVVDDataContext();

            if (ddlLOPHOC.SelectedIndex >= 0)
            {
                var lst_mh = (from cl in db.F_LOP_MONHOCs
                              where cl.MALH.Equals(ddlLOPHOC.SelectedValue)
                              select new
                              {
                                  MAMH = cl.MAMH,
                                  TENMH = cl.LST_MONHOC.TENMH
                              }).ToList();
                ddlMONHOC.DataSource = lst_mh;

            }
            else
            {

                List<LST_MONHOC> lst_mh = (from mh in db.LST_MONHOCs
                                           select mh).ToList();
                ddlMONHOC.DataSource = lst_mh;

            }

            ddlMONHOC.DataValueField = "MAMH";
            ddlMONHOC.DataTextField = "TENMH";
            ddlMONHOC.DataBind();

        }

        protected void grvDiemthi_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.InitInsertCommandName)
            {
                e.Canceled = true;
                System.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();

                newValues["MAHV"] = String.Empty;
                newValues["MALH"] = String.Empty;
                newValues["MAMH"] = String.Empty;
                newValues["DIEM"] = String.Empty;
                newValues["LANTHI"] = String.Empty;
                newValues["NGAYTHI"] = String.Empty;
                newValues["GHICHU"] = String.Empty;
                e.Item.OwnerTableView.InsertItem(newValues);
            }
            if (e.CommandName.Equals("ChamDiem"))
            {
                BVVDDataContext db = new BVVDDataContext();
                foreach (GridDataItem dr in grvDiemthi.Items)
                {
                    string mahv = dr["MAHV"].Text;
                    string malh = dr["MALH"].Text;
                    string mamh = dr["MAMH"].Text;
                    DateTime ngaythi = rdpNGAYTHI.SelectedDate.Value;
                    decimal diemthi = Convert.ToDecimal((dr.FindControl("txtDIEM") as RadNumericTextBox).Value);
                    int lanthi = Convert.ToInt32((dr.FindControl("txtLANTHI") as RadNumericTextBox).Value);
                    F_DIEMTHI obj = new F_DIEMTHI
                    {
                        MAHV = mahv,
                        MALH = malh,
                        MAMH = mamh,
                        NGAYTHI = ngaythi,
                        DIEM = diemthi, //String.IsNullOrEmpty(diemthi.ToString())?100:diemthi,
                        LANTHI = String.IsNullOrEmpty(lanthi.ToString()) ? 1 : lanthi,
                        TRANGTHAI = "1"
                    };
                    checkRowExist(obj);


                }
                grvDiemthi.Rebind();
                rnAlert.Text = "Lưu điểm thành công ";
                rnAlert.Show();
            }
        }

        private string checkRowExist(F_DIEMTHI fc)
        {
            BVVDDataContext db = new BVVDDataContext();
            F_DIEMTHI value = (from ck in db.F_DIEMTHIs
                               where ck.MALH.Equals(fc.MALH) && ck.MAMH.Equals(fc.MAMH)
                                       && ck.MAHV.Equals(fc.MAHV) && ck.NGAYTHI.Value.Equals(fc.NGAYTHI)
                               select ck).SingleOrDefault();
            if (value == null)
            {
                if (fc.DIEM < 11)
                {
                    db.F_DIEMTHIs.InsertOnSubmit(fc);
                    db.SubmitChanges();
                    return "Add";
                }
                else
                {
                    return "Dont Save";
                }
            }
            else if (!value.DIEM.Equals(fc.DIEM) || !value.LANTHI.Equals(fc.LANTHI))
            {
                value.DIEM = fc.DIEM;
                value.LANTHI = fc.LANTHI;
                db.SubmitChanges();
                return "Update";
            }
            else
            {

                return "Cancel";
            }

        }


    }
}